package com.budwk.app.sqfw.northstation.controllers;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.budwk.app.sqfw.northstation.models.DeviceChannel;
import com.budwk.app.sqfw.northstation.service.NsdeviceinfoService;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.sqfw.northstation.models.Ns_trackrecord;
import com.budwk.app.sqfw.northstation.service.NsTrackrecordService;
import org.nutz.aop.interceptor.async.Async;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@IocBean
@At("/platform/northstation/trackrecord")
@ApiDefinition(tag = "Ns_trackrecord设备记录")
@SLog(tag = "设备经纬度记录")
@Slf4j
public class NsTrackrecordController{
    @Inject
    private NsTrackrecordService nsTrackrecordService;


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询Ns_trackrecord")
    @ApiFormParams(
        value = {
            @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
            @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
            @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
            @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
        },
        implementation = Ns_trackrecord.class
    )
    @ApiResponses(
    implementation = Ns_trackrecord.class
    )
    public Result<?> list(@Param("..")Ns_trackrecord bean,@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }

        if (bean!=null && bean.getName() !=null && Strings.isNotBlank(bean.getName().toString())) {
            cnd.and("name","=",bean.getName());
        }

        if (bean!=null &&bean.getLatitude() !=null && Strings.isNotBlank(bean.getLatitude().toString())) {
            cnd.and("latitude","=",bean.getLatitude());
        }

        if (bean!=null &&bean.getLongitude() !=null && Strings.isNotBlank(bean.getLongitude().toString())) {
            cnd.and("longitude","=",bean.getLongitude());
        }

        if (bean!=null &&bean.getType() !=null && Strings.isNotBlank(bean.getType().toString())) {
            cnd.and("type","=",bean.getType());
        }

        if (bean!=null &&bean.getUsername() !=null && Strings.isNotBlank(bean.getUsername().toString())) {
            cnd.and("username","=",bean.getUsername());
        }

        if (bean!=null &&bean.getUserid() !=null && Strings.isNotBlank(bean.getUserid().toString())) {
            cnd.and("userid","=",bean.getUserid());
        }
        if (bean!=null &&bean.getCreatedAt() != null && Strings.isNotBlank(bean.getCreatedAt().toString())) {
            cnd.and("createDate", ">", bean.getCreatedAt());
        }
        return Result.data(nsTrackrecordService.listPage(pageNo, pageSize, cnd));
    }




    @At("/getDeviceInfo")
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询Ns_trackrecord")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Ns_trackrecord.class
    )
    @ApiResponses(
            implementation = Ns_trackrecord.class
    )
    public Result<?> getDeviceInfo(@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        List<DeviceChannel>  list =nsTrackrecordService.getDeviceInfo();
        return Result.data(list);
    }



    public void inserttrackrecord() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        Runnable task = new Runnable() {
            @Override
            public void run() {
                nsTrackrecordService.installTrackrecordInfo();
            }
        };
        scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增Ns_trackrecord")
    public Result<?> create(@Param("..")Ns_trackrecord nsTrackrecord) {

        Ns_trackrecord vo = new Ns_trackrecord();
        vo.setDeviceid(nsTrackrecord.getDeviceid());
        Ns_trackrecord Trackrecordinfo= nsTrackrecordService.Trackrecordinfo(vo);
        boolean isDistanceMoreThanOneMeter=false;
        if(Trackrecordinfo!=null) {
            isDistanceMoreThanOneMeter =  nsTrackrecordService.isDistanceMoreThanOneMeter(Double.parseDouble(Trackrecordinfo.getLatitude()), Double.parseDouble(Trackrecordinfo.getLongitude()), Double.parseDouble(nsTrackrecord.getLatitude()), Double.parseDouble(nsTrackrecord.getLongitude()));
        }
        if(Trackrecordinfo==null || isDistanceMoreThanOneMeter) {
            nsTrackrecord.setCreatedBy(SecurityUtil.getUserId());
            nsTrackrecordService.insert(nsTrackrecord);
            return Result.success();
        }
        return Result.success();
    }




    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改Ns_trackrecord")
    @ApiFormParams(
        implementation = Ns_trackrecord.class
    )
    @ApiResponses
    @SLog(tag = "修改Ns_trackrecord", value = "${args[0].id}")
    public Result<?> update(@Param("..")Ns_trackrecord nsTrackrecord, HttpServletRequest req) {
        // List<DeviceChannel> getDeviceInfo();
        nsTrackrecord.setUpdatedBy(SecurityUtil.getUserId());
        nsTrackrecordService.updateIgnoreNull(nsTrackrecord);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取Ns_trackrecord")
    @ApiFormParams(
        {
            @ApiFormParam(name = "id", description = "唯一标识",required = true, check = true)
        }
    )
    public Result<?> getData(@Param("id")String id, HttpServletRequest req) {
        Ns_trackrecord nsTrackrecord = nsTrackrecordService.fetch(id);
        if (nsTrackrecord == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        return Result.data(nsTrackrecord);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除Ns_trackrecord")
    @ApiFormParams(
        {
            @ApiFormParam(name = "id", description = "唯一标识",required = true, check = true)
        }
    )
    @SLog(tag = "删除Ns_trackrecord", value = "${args[0]}")
    public Result<?> delete(@Param("id")String id, HttpServletRequest req) {
        Ns_trackrecord nsTrackrecord = nsTrackrecordService.fetch(id);
        if (nsTrackrecord == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        nsTrackrecordService.delete(id);
        req.setAttribute("_slog_msg", nsTrackrecord.getId());
        return Result.success();
    }
}
